package pub.wkq.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <h1>二维码工具类</h1>
 * @author wangkaiqi@g7e6.com.cn
 * @date 2023/06/14
 */
public class QRCodeGenerator {
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 300;
    private static final String DEFAULT_FORMAT = "png";

    /**
     *
     * @param text
     * @param foregroundColor
     * @param backgroundColor
     * @return
     */
    public static String generateQRCodeAndUploadToOSS(String text,  Color foregroundColor, Color backgroundColor) {
        return generateQRCodeAndUploadToOSS(text, DEFAULT_WIDTH, DEFAULT_HEIGHT, UUID.randomUUID().toString().replace("-", ""), DEFAULT_FORMAT, foregroundColor, backgroundColor);
    }

    /**
     * 生成默认宽高、后缀、默认颜色的二维码
     *
     * @param text     内容
     * @param fileName 文件名
     */
    public static String generateQRCodeAndUploadToOSS(String text, String fileName) {
        return generateQRCodeAndUploadToOSS(text, DEFAULT_WIDTH, DEFAULT_HEIGHT, fileName, DEFAULT_FORMAT);
    }

    /**
     * 生成白色背景黑色内容的二维码
     *
     * @param text     内容
     * @param width    宽度
     * @param height   高度
     * @param fileName 文件名
     * @param format   文件名后缀
     */
    public static String generateQRCodeAndUploadToOSS(String text, int width, int height, String fileName,
                                                      String format) {
        return generateQRCodeAndUploadToOSS(text, width, height, fileName, format, Color.BLACK, Color.WHITE);
    }

    /**
     * 生成二维码并上传至 OSS
     *
     * @param text            内容
     * @param width           宽度
     * @param height          高度
     * @param fileName        文件名
     * @param format          格式，图片后缀
     * @param foregroundColor 二维码颜色
     * @param backgroundColor 二维码背景色
     */
    public static String generateQRCodeAndUploadToOSS(String text, int width, int height, String fileName,
                                                      String format, Color foregroundColor, Color backgroundColor) {
        String path = null;
        try {
            // 生成二维码图片
            BufferedImage image = generateQRCodeImage(text, width, height, foregroundColor, backgroundColor);

            // 保存生成的二维码图片到临时文件
            File tempFile = File.createTempFile("qrcode", "." + format);
            ImageIO.write(image, format, tempFile);

            // 上传二维码图片到OSS
            path = uploadImageToOSS(tempFile, fileName);

            // 删除临时文件
            tempFile.delete();
            return path;
        } catch (Exception e) {
            System.err.println("生成并上传二维码到OSS时发生错误：" + e);
            return "生成并上传二维码到OSS时发生错误";
        }
    }

    /**
     * 生成二维码图片
     *
     * @param text            内容
     * @param width           宽度
     * @param height          高度
     * @param foregroundColor 颜色
     * @param backgroundColor 背景色
     * @return 二维码
     * @throws Exception
     */
    private static BufferedImage generateQRCodeImage(String text, int width, int height, Color foregroundColor,
                                                     Color backgroundColor) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        graphics.setColor(backgroundColor);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(foregroundColor);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (bitMatrix.get(x, y)) {
                    graphics.fillRect(x, y, 1, 1);
                }
            }
        }

        return image;
    }

    private static String uploadImageToOSS(File file, String fileName) {
        String endpoint = "oss-cn-chengdu.aliyuncs.com"; // OSS的Endpoint
        String accessKeyId = "LTAI5tRGiDtSEUsqnW7PbBic"; // 访问密钥ID
        String accessKeySecret = "Nt1cNogA5UraNaseW6UKNVzFakvnZF"; // 访问密钥Secret
        String bucketName = "wkq-img"; // 存储桶名称
        String baseUrl = "https://img.wkq.pub/";
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件到OSS
            ossClient.putObject(bucketName, fileName, file);

            System.out.println("二维码图片上传成功！地址为：https://img.wkq.pub/" + fileName);
            return baseUrl + fileName;
        } catch (Exception e) {
            System.err.println("上传二维码图片到OSS时发生错误：" + e);
            return "上传二维码图片到OSS时发生错误";
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}
